<template>
  <div class="tr-select-filter-box">
    <div class="title ft-14 cr-bk-9 mg-bt-16 fw-600">{{ title }}</div>
    <el-input
      placeholder="请输入查询关键字"
      prefix-icon="el-icon-search"
      v-model="treeFilter"
      clearable
    ></el-input>
    <el-scrollbar>
      <el-tree
        class="tree-select"
        :data="treeData"
        :props="defaultProps"
        @node-click="handleNodeClick"
        :expand-on-click-node="expandOnclickNode"
        :check-on-click-node="true"
        highlight-current
        ref="tree"
        :lazy="lazy"
        :load="lazy ? loadFun : undefined"
        :node-key="nodeKeySWord"
        :default-expanded-keys="expandKey"
        :default-expand-all="defaultExpandAll"
        :filter-node-method="filterNode"
        @node-expand="handleNodeExpand"
        @node-collapse="handleNodeCollapse"
      >
        <span slot-scope="{ data }">
          <span>{{ data[showWord] }}</span>
        </span>
      </el-tree>
    </el-scrollbar>
  </div>
</template>

<script>
export default {
  name: "TrSelectTree",
  props: {
    title: {
      type: String,
      default: "部门列表",
    },
    loadFun: {
      type: Function,
    },
    defaultExpandAll: {
      type: Boolean,
      default: false,
    },
    expandOnclickNode: {
      type: Boolean,
      default: false,
    },
    nodeKeySWord: {
      type: String,
      default: "id",
    },
    lazy: {
      type: Boolean,
      default: false,
    },
    treeData: {
      type: Array,
      default: () => [],
    },
    showWord: {
      type: String,
      default: "title",
    },
    valueWord: {
      type: String,
      default: "value",
    },
    defaultProps: {
      type: Object,
      default: () => ({
        children: "children",
        label: "label",
        isLeaf: (data) => {
          return !data.hasChildren;
        },
      }),
    },
  },
  data: () => ({
    treeFilter: "",
    expandKey: [],
    currentNodeKey: "",
  }),
  watch: {
    treeFilter(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    reset(type) {
      if (type === "all") {
        this.currentNodeKey = "";
        this.expandKey = [];
      }

      this.$refs.tree.setCurrentKey(null);
    },
    handleNodeClick(data) {
      this.treeFilter = "";
      this.currentNodeKey = data.id;

      this.$emit("select-back", data);
    },
    handleNodeExpand(data) {
      this.expandKey.push(data.id);
    },
    handleNodeCollapse(data) {
      this.expandKey = this.expandKey.filter((item) => item !== data.id);
    },
    setCurrentKey(key = this.currentNodeKey) {
      this.$refs.tree.setCurrentKey(key);
    },
    filterNode(value, data) {
      if (!value) return true;
      return data[this.showWord].indexOf(value) !== -1;
    },
  },
};
</script>

<style scoped lang="scss">
.tr-select-filter-box {
  height: 100%;
  width: 100%;
  .el-scrollbar {
    height: calc(100% - 32px);
    margin-top: 8px;
  }
}
</style>
